<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>搜索框输入文字自动提示</title>
	<link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css">
	<style type="text/css">
		.container {
			padding-top: 150px;
		}

		.list-group {
			display: none;
		}
	</style>
</head>

<body>
	<div class="container">
		<div class="form-group">
			<input type="text" class="form-control" placeholder="请输入搜索关键字" id="search">
			<ul class="list-group" id="list-box">

			</ul>
		</div>
	</div>
	<script src="/js/ajax.js"></script>
	<script src="/js/template-web.js"></script>
	<!-- 创建模板文件 -->
	<script type="text/html" id="tpl">
		{{each result}}
		<li class="list-group-item">{{$value}}</li>
		{{/each}}
	</script>

	<script>
		// 获取搜索框
		let search = document.getElementById('search');
		// 获取提示文字的存放容器
		let listbox = document.getElementById('list-box');
		// 存储定时器的变量
		let timer = null;
		// 当用户在文本框中输入的时候触发
		search.oninput = function () {

			clearTimeout(timer);

			let key = this.value;

			if (key.trim().length == 0) {

				listbox.style.display = 'none';

				return;
			}

			timer = setTimeout(function () {
				ajax({
					url: '/searchAutoPrompt',
					data: {
						key: key
					},
					success: function (result) {

						let html = template('tpl', {
							result: result
						});

						listbox.innerHTML = html;

						listbox.style.display = 'block';
					}

				});

			}, 800);
		};
	</script>
</body>

</html>